package com.tanhua.dubbo.api.mongo;

import com.sun.org.apache.regexp.internal.RECompiler;
import com.tanhua.domain.mongo.RecommendUser;
import com.tanhua.domain.vo.PageResult;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

/**
 * 今日佳人服务实现类
 */
@Service
public class RecommendUserApiImpl implements RecommendUserApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 根据当前登录的用户id查询佳人用户表 最匹配用户对象（1条记录）
     * db.recommend_user.find({toUserId:1}).sort({score:-1}).limit(1);
     *
     * @param toUserId
     * @return
     */
    @Override
    public RecommendUser queryMaxScoreByToUserId(Long toUserId) {
        Query query = new Query();
        //{toUserId:1}
        query.addCriteria(Criteria.where("toUserId").is(toUserId));
        //sort({score:-1})
        //query.with(Sort.by(Sort.Direction.DESC, "score"));
        query.with(Sort.by(Sort.Direction.ASC, "userId"));
        //limit(1)
        query.limit(1);
        return mongoTemplate.findOne(query, RecommendUser.class);
    }

    /**
     * 跟当前登录用户id 分页参数 分页查询佳人列表数据
     *
     * @param page
     * @param pagesize
     * @param currentUserId
     * @return
     */
    @Override
    public PageResult<RecommendUser> queryPageByUserId(Integer page, Integer pagesize, Long currentUserId) {
        //1.查询recommendUser表总记录数
        Query query = new Query();
        query.addCriteria(Criteria.where("toUserId").is(currentUserId));//当前用户id
        query.limit(pagesize).skip((page - 1) * pagesize);
        long counts = mongoTemplate.count(query, RecommendUser.class);
        //2.查询当前页面要展示的数据
        List<RecommendUser> recommendUserList = mongoTemplate.find(query, RecommendUser.class);
        //3.将数据封装返回
        long pages = (counts / pagesize) + (counts%pagesize > 0 ? 1:0);
        return new PageResult<>(counts,(long)pagesize,pages,(long)page,recommendUserList);
    }
    /**
     * 根据佳人用户id 与 当前用户id 查询缘分值
     * @param userId 佳人用户id
     * @param toUserId 当前用户id
     * @return
     */
    @Override
    public Double queryForScore(Long userId, Long toUserId) {
        Query query = new Query();
        //{toUserId:1}
        query.addCriteria(Criteria.where("userId").is(userId).and("toUserId").is(toUserId));
        RecommendUser recommendUser = mongoTemplate.findOne(query, RecommendUser.class);
        if(recommendUser == null){
            return 99d;
        }
        return recommendUser.getScore();
    }
}
